package org.six11.ss.server;

import java.util.HashMap;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.six11.util.Debug;
import org.six11.util.adt.MultiState;

/**
 * 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class WebappEventListener implements HttpSessionListener {

  public void sessionCreated(HttpSessionEvent ev) {
    // TODO: since I am using sessions for the web pages, I can't set the inactive interval to
    // a short value. I will need to implement some sort of reaper.
    // ev.getSession().setMaxInactiveInterval(20);
    
    ev.getSession().setMaxInactiveInterval(60 /* seconds */ * 40 /* minutes */);
  }

  @SuppressWarnings("unchecked")
  public void sessionDestroyed(HttpSessionEvent ev) {
    // bug("Session destroyed: " + ev.getSession().getId());
    Router r = Router.instance;
    MultiState state = r.getState();
    HashMap<String, AppletMessageHandler> appletMessageHandlers = (HashMap<String, AppletMessageHandler>) state
        .getValue(ServerStateNames.HANDLERS);
    LogoutHandler logOut = (LogoutHandler) appletMessageHandlers.get("logout");
    if (logOut == null) {
      // bug("Can't access the LogoutHandler while expiring a session.");
    } else {
      Session s = AppletMessageHandler.sessionFactory.getCurrentSession();
      Transaction tx = null;
      boolean commitAfter = true;
      if (s.getTransaction() == null) {
        tx = s.beginTransaction();
      } else {
        tx = s.getTransaction();
        commitAfter = false;
      }
      try {
        logOut.logout(ev.getSession().getId());
      } finally {
        if (commitAfter) {
          tx.commit();
        }
      }
    }
  }

  private static void bug(String what) {
    Debug.out("WebappEventListener", what);
  }

}
